// pages/myNian/payCard/payCard.js
var common = require("../../../public.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nianList:[],
        colors:'',
        obj:{},  //年刊详情
        detaiList:[],
        show: false,
        values: '',
        showss:true,
        pagecount:1,
        totalArr:[],//分页总数据
        qrcodeid:"",
        cardId:"",
        distributorId:'' //支付和激活需要的
    },
    // 获取未购买会员卡列表
    reLists(){
      var that = this
      common.get('/userAnnualCard/getCardList', {cardId:this.data.cardId}, res => {
        if (res.status === 200) {
        that.setData({
          obj:res.data[0]
        },
        ()=>{
          
        })
        } else {
          common.showRequestErrMsg(res)
        }
      })
},    
    onChange(event) {
      this.setData({
        values:event.detail
      })
    },
    ji_huo(){
      var that = this 
      common.getLocalUserInfo(function (success, data) {
        if (success) {
          that.setData({
            show:true
          })
        } else {
          common.showLoginPage() 
        }
        })
    },
    // 激活碼
    fn(){
      var that = this
       var temp = {
         distributorId:that.data.distributorId,
         cardId:that.data.cardId,
         userId:that.data.userInfo.id,
         code:that.data.values,
         token:that.data.token
       }
      common.get('/userAnnualCard/buyAnnualCard/activationCode', temp, res => {
        if (res.status === 200) {
          // 登录已超时，请重新登录
          if(res.msg=="登录已超时，请重新登录"){
            common.showLoginPage() 
            return
          }
          wx.showToast({
            title: res.data,
            duration:3000,//显示时长
            icon: 'none',
            success:function(){ 
              setTimeout(function() {
                wx.navigateTo({
                  url:"/packageA/pages/indexnian/indexni"
                })
             }, 1000);
            }
             })
        } else {
          common.showRequestErrMsg(res)

        }
    })
    },
    getUserInfo(event) {
      this.setData({
        show:false
      },
      ()=>{
       this.fn()   
      })  
    },
    onClose() {
      this.setData({ show: false });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    // 会员卡详情下面的列表
cardsList_two(id){
    var that = this
    common.get('/userAnnualCard/getCardProductListForApplets', {
          cardId:id, 
          productType:"",
          userId:that.data.userInfo.id,

          token:that.data.token
        }, res => {
      if (res.status === 200) {
        if(id==7){
          // var items = {
          //   discount: 0, //免费
          //   frequency: 12,
          //   productName: "中国石油加油券（联系客服）",
          //   singleValue: 15, 
          // }
          var itemss = {
            discount: 0, //免费
            frequency: 1,
            productName: "中国移动咪咕视频会员(联系客服)",
            singleValue: 180, 
          }
          res.data.unshift(itemss)
        }
        for( var i=0,len=res.data.length;i<len;i++){
          res.data[i].discount=(res.data[i].discount*10).toFixed(1)
          res.data[i].num_string = res.data[i].discount.toString()
          if( res.data[i].num_string.indexOf('.')!=-1){  //包含
            res.data[i].len = res.data[i].num_string.split(".")[1]
             res.data[i]. newnum = 0
             if(res.data[i].len!=0){
              res.data[i]. newnum = res.data[i].discount
             }else {
              res.data[i]. newnum =  res.data[i].num_string.split(".")[0]
             }
           
          }
        }
        that.setData({
               nianList:res.data
             })
              var pagecount=1//默认第一页
              var result =[]; 
              for(var i=0,len=res.data.length;i<len;i+=5){
                result.push(res.data.slice(i,i+5));
             }
             if(pagecount==1){
              if(result[0]){
                that.setData({
                  totalArr:result,
                  detaiList:result[0],
                  pagecount:pagecount,
                  showss:true
                })
              }else{
                that.setData({
                  totalArr:result,
                  detaiList:[],
                  pagecount:pagecount
                })
            }}
      } else {
        common.showRequestErrMsg(res)
      }
  })
  },
    // 查看更多  
click_data(){
  var pageCount = this.data.pagecount +1
  if(this.data.totalArr.length==pageCount){
        this.setData({
           showss:false
        })
  }
  if(this.data.totalArr[pageCount-1]){
    this.setData({
      detaiList:[...this.data.detaiList,...this.data.totalArr[pageCount-1]],
      pagecount:pageCount,
   })
  } 
},

click_shou(){
  this.setData({
    detaiList:this.data.totalArr[0],
     showss:true,
     pagecount:1,
 })
},
    //   去支付 
    go_pay(){
      var that = this
      common.getLocalUserInfo(function (success, data) {
        if (success) {
          let tempJson = {
            userId:that.data.userInfo.id,
            cardId:that.data.cardId,
            openid:that.data.openid,
            token:that.data.token,
            distributorId:that.data.distributorId
          }
            common.wxPayRequest("/wxxcxPayForAnnualCard", tempJson, function (res) {

              if(res.msg=="登录已超时，请重新登录"){
                common.showLoginPage() 
                return
              }
              if(res.status== 400){
                  wx.showToast({
                    title: res.msg,
                    duration:3000,//显示时长
                    icon: 'none',
                    success:function(){ 
                      setTimeout(function() {
                        wx.navigateTo({
                          url:"/packageA/pages/indexnian/indexni"
                        })
                     }, 1000);
                    },//接口调用成功
                  })
                  return
              }
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr,
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                'success': function (res) {
                  common.showToast('支付成功', 'success')
                  wx.navigateTo({
                    url:"/packageA/pages/indexnian/indexni"
                  })
                },
                'fail': function (res) {
                  console.log(res)
                  if (res.errMsg === 'requestPayment:fail cancel') {
                  
                  } else {
                    common.showToast(res.errMsg)
                  }
                }
              })
            })
        } else {
          console.log("没有登录")
          common.showLoginPage() 
        }
        })
        
      },
    onLoad: function (opt) {
        var that =this
        if (opt.q){
          let scan_url = decodeURIComponent(opt.q);
          let video_id = scan_url.match(/\d+/) //提取链接中的数字，也就是链接中的参数id，/\d+/ 为正则表达式
         var distributorId = video_id['input'].split("=")
          common.getLocalUserInfo(function (success, data) {
            if (success) {
              that.setData({
                userInfo: data.user,
                token: data.token,
                openid:data.openid,
                cardId:video_id[0],
                distributorId:distributorId[3] ?  distributorId[3] : ''
              }, function () {
                this.reLists()  //获取这张会员卡的信息
                that.cardsList_two(that.data.cardId) //这张会员卡下面的权益
                this.isPay()
              })
            } else {
              common.showLoginPage()
             
            }
          })
           return
          //  公眾號
          }else{
            common.getLocalUserInfo(function (success, data) {
              console.log(data)
              if (success) {
                that.setData({
                  userInfo:data.user,
                  token: data.token,
                  openid:data.openid,
                  cardId:opt.cardId ,
                  distributorId:opt.distributorId ?  opt.distributorId : ''
                }, function () {
                  this.reLists()
                  that.cardsList_two(that.data.cardId) //这张会员卡下面的权益
                  this.isPay()
                })
              } else {
                common.showLoginPage()
              }
            })
          }
    },
    // 时间戳
    time(time) {
      return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },

    // 判断是否支付
    isPay(){
      common.get('/userAnnualCard/checkUserBoughtCard', { 
         userId:this.data.userInfo.id,
         cardId:this.data.cardId,
         token:this.data.token
      }, res => {
          console.log(res)
        if (res.status === 1 ){
            wx.navigateTo({
              url: '/packageA/pages/indexnian/indexni',
            })
        } 
     
    })
    },
    // 跳转会员卡协议
    click_cie(){
      wx.navigateTo({
        url: '/packageB/pages/agreement/agreement',
      })
    },
    onShareAppMessage: function () {
      return {
        title: this.data.title,
        path: '/pages/myNian/payCard/payCard?cardId=' + this.data.cardId + '&distributorId=' + this.data.distributorId,
        // imageUrl: '/images/home.png',
        success: (res) => {
          // 分享成功
        },
        fail: (res) => {
          // 分享失败
        }
      }
    },
})